package cz.af.portletExams.backend.rest.converter;

import cz.af.portletExams.model.Exam;
import org.jdom.Element;
import org.jdom.Namespace;
import org.joda.time.LocalDateTime;

public class ExamConverter extends GenericExamModelConverter<Exam> {

    @Override
    protected Exam convertToObject(Element rootElement) {
        final Namespace atomNamespace = rootElement.getNamespace();
        final Namespace defaultNamespace = rootElement.getNamespace("");
        final Namespace xlinkNamespace = rootElement.getNamespace("xlink");

        final Exam exam = new Exam();

        final String[] split = rootElement.getChild("id", atomNamespace).getText().split(":");
        exam.setId(split[split.length - 1]);


        final Element content = rootElement.getChild("content", atomNamespace);

        exam.setCapacity(Integer.parseInt(content.getChild("capacity", defaultNamespace).getText()));
        exam.setOccupied(Integer.parseInt(content.getChild("occupied", defaultNamespace).getText()));

        final String startDate = content.getChild("startDate", defaultNamespace).getText();
        final LocalDateTime localDateTime = LocalDateTime.parse(startDate);
        exam.setDate(localDateTime);

        final String course = content.getChild("course", defaultNamespace).getAttribute("href", xlinkNamespace).getValue();
        final String[] strings = course.split("/");
        exam.setSubjectId(strings[1]);

        return exam;
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return Exam.class == clazz;
    }
}
